package com.zy.dao.impl;

import com.zy.dao.FindUserByNameDao;
import com.zy.entity.User;
import com.zy.utils.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class FindUserByNameDaoImpl implements FindUserByNameDao {
    @Override
    public List<User> findUserByName(String name) {
        List<User> users = new ArrayList<>();
        String sql = "SELECT * FROM tb_user WHERE username LIKE ?";

        try (Connection connection = JdbcUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            preparedStatement.setString(1, "%" + name + "%");
            ResultSet resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setUserName(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                user.setUserType(resultSet.getInt("user_type"));
                user.setBalance(resultSet.getDouble("balance"));
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return users;
    }
} 